<template>
  <div id="box">
    <el-card
      v-loading="tableLoading"
      shadow="never"
      :class="{ pointerEvents: tableLoading }"
    >
      <div>
        <el-form
          ref="queryForm"
          :inline="true"
          :model="queryData"
          class="demo-form-inline"
        >
          <el-form-item label="时间范围" prop="queryDate">
            <el-date-picker
              v-model="queryData.queryDate"
              type="monthrange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="yyyy-MM"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="统计质控" prop="querytype">
            <el-select
              v-model="queryData.querytype"
              placeholder="统计质控"
              clearable
            >
              <el-option
                v-for="(item, index) in optionData"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr">
            <el-button type="primary" @click="queryEchart()">查询</el-button>
            <el-button @click="resetForm('queryForm')">重置</el-button>
          </el-form-item>
          <el-divider class="dividerLine" />
        </el-form>
      </div>
      <div>
        <el-row>
          <el-col v-show="pie_or_line == 'pie'" :span="10">
            <div ref="chart" class="echarts-dom" />
          </el-col>
          <el-col v-if="monthTableData.length > 0" :span="14">
            <el-table
              :data="monthTableData"
              style="width: 100%"
              border
              size="mini"
              height="500"
            >
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column type="index" width="50" align="center">
                <template slot-scope="scope" align="center">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="month" label="月份" align="center" />
              <el-table-column prop="count" label="数量" align="center" />
              <el-table-column
                fixed="right"
                label="操作"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    class="mr-10"
                    type="text"
                    @click="monthDetails(scope.row)"
                  >查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col
            v-if="tableData.length > 0"
            :span="24"
            style="margin-top: 20px;"
          >
            <el-table
              v-loading="tableLoading"
              :data="tableData"
              style="width: 100%"
              border
              size="mini"
            >
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column type="index" width="50" align="center">
                <template slot-scope="scope" align="center">
                  {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <!-- <el-table-column prop="pat_id" label="主键" align="center" /> -->
              <el-table-column
                prop="pat_type_name"
                label="患者类型"
                align="center"
              />
              <el-table-column prop="user_name" label="医生名" align="center" />
              <el-table-column
                prop="pat_name"
                label="患者姓名"
                align="center"
              />
              <el-table-column
                prop="pat_sex_name"
                label="性别"
                align="center"
                width="55"
              />
              <el-table-column
                prop="age"
                label="年龄"
                align="center"
                width="55"
              />
              <el-table-column
                prop="plan_name"
                label="随访名称"
                align="center"
              />

              <el-table-column
                fixed="right"
                label="操作"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    class="mr-10"
                    type="text"
                    @click="getRowKey(scope.row)"
                  >跳转查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="pagination"
              :current-page.sync="pageNum"
              :page-sizes="[10, 20]"
              :page-size.sync="pageSize"
              layout="sizes, prev, pager, next ,total"
              :total="count"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import echarts from 'echarts'
import {
  followYzyStatisticsQuery,
  followYzyStatisticsQueryMonth,
  followYzyStatisticsQueryInfo,
  followYzyStatisticsQueryInfoCount
} from '@/api/statistical/statistical-analysis'
export default {
  data() {
    return {
      queryData: {
        queryDate: [
          new Date(new Date().getFullYear() - 1, new Date().getMonth()),
          new Date(new Date().getFullYear(), new Date().getMonth())
        ],
        querytype: 'query1'
      },
      pageSize: 10,
      pageNum: 1,
      count: 0,
      pie_or_line: 'pie',
      // tableCol: 24,
      tableData: [],
      monthTableData: [],
      tableLoading: false,
      optionData: {
        query1: '已有随访记录的患者性别比例',
        query2: '已有随访记录的患者年龄区间比例',
        query3: '已有随访记录的患者慢病疾病类型比例',
        query4: '随访危险等级比例',
        query5: '依从性高的患者比例'
      },
      chartData: {
        queryDate: [], // 查询日期备份
        querytype: '', // 查询下拉备份
        titleText: '无数据', // 图表数据
        legendData: [], // 图表数据
        type: '', //  根据情况来定
        data: [] // 图表数据
      },
      queryConditionBackup: {} // 查询数据备份
    }
  },

  computed: {},
  created() {},
  mounted() {
    this.queryEchart()
  },
  methods: {
    /*
     * 查询echart图数据
     */
    queryEchart() {
      if (
        this.queryData.queryDate.length === 0 ||
        this.queryData.queryDate.length < 2
      ) {
        this.$message.warning('时间范围不能为空')
        return false
      }
      if (!this.queryData.querytype) {
        this.$message.warning('统计质控不能为空')
        return false
      }
      this.recoverParams()
      this.tableData = []
      this.monthTableData = []
      this.chartData = {
        queryDate: [], // 查询日期备份
        querytype: '', // 查询下拉备份
        titleText: '无数据', // 图表数据
        legendData: [], // 图表数据
        data: [], // 图表数据
        titleX: [] // x轴数据
      }
      this.chartData.titleText = this.optionData[this.queryData.querytype]
      const params = {
        querytype: this.queryData.querytype,
        hospitalId: this.$store.getters.hospitalId
      }
      if (!!this.queryData.queryDate && this.queryData.queryDate.length === 2) {
        if (this.queryData.queryDate[0] instanceof Date) {
          // 如果是date日期就格式化
          params.startTime =
            this.queryData.queryDate[0].getFullYear() +
            '-' +
            (this.queryData.queryDate[0].getMonth() + 1)
          params.endTime =
            this.queryData.queryDate[1].getFullYear() +
            '-' +
            (this.queryData.queryDate[1].getMonth() + 1)
        } else {
          params.startTime = this.queryData.queryDate[0]
          params.endTime = this.queryData.queryDate[1]
        }
      }
      followYzyStatisticsQuery(params).then(res => {
        this.queryConditionBackup = params
        // this.tableCol = 14
        this.chartData.data = []
        this.chartData.legendData = []
        // 根据不同项进行数据格式化
        this.dataFormatQuery(res.data, this.queryData.querytype)
        this.$nextTick(() => {
          this.echartPie()
        })
      })
    },

    // 根据不同项进行饼图数据格式化
    dataFormatQuery(data, queryX) {
      console.log(queryX)
      if (queryX === 'query1') {
        this.chartData.legendData = ['男', '女', '未知']
        this.chartData.data.push(
          { value: data.part1, name: '男', type: 'part1' },
          { value: data.part2, name: '女', type: 'part2' },
          { value: data.part3, name: '未知', type: 'part3' }
        )
      } else if (queryX === 'query2') {
        data.forEach(item => {
          const title = `${item.age}0 ~ ${item.age}9`
          this.chartData.legendData.push(title)
          this.chartData.data.push({
            value: item.count,
            name: title,
            type: item.age
          })
        })
      } else if (queryX === 'query3') {
        data.forEach(item => {
          const patName = item.pat_type_name || '未知'
          const patCode = item.pat_type_code || ''
          this.chartData.legendData.push(patName)
          this.chartData.data.push({
            value: item.count,
            name: patName,
            type: patCode
          })
        })
      } else if (queryX === 'query4') {
        data.forEach(item => {
          const patName = item.pat_type_name || '未知'
          const patCode = item.chronic_disease_grade || ''
          this.chartData.legendData.push(patName)
          this.chartData.data.push({
            value: item.count,
            name: patName,
            type: patCode
          })
        })
      } else if (queryX === 'query5') {
        this.chartData.legendData = ['差', '中等', '好', '未知']
        this.chartData.data.push(
          { value: data.part1, name: '差', type: 'part1' },
          { value: data.part2, name: '中等', type: 'part2' },
          { value: data.part3, name: '好', type: 'part3' },
          { value: data.part4, name: '未知', type: 'part4' }
        )
      }
      // console.log(this.chartData)
    },

    /*
     *根据echart图数据查询表格
     */
    queryList() {
      this.queryConditionBackup.type = this.queryConditionBackup.type || ''
      this.monthTableData = []
      this.queryConditionBackup.pageNum = undefined
      this.queryConditionBackup.pageSize = undefined
      followYzyStatisticsQueryMonth(this.queryConditionBackup).then(res => {
        this.monthTableData = res.data
        this.tableLoading = false
      })
    },
    monthDetails(row = {}) {
      this.tableData = []
      this.recoverParams()
      this.queryConditionBackup.month = row.month
      this.queryDetailsTable()
    },
    queryDetailsTable() {
      const params = {
        querytype: this.queryConditionBackup.querytype,
        startTime: this.queryConditionBackup.month,
        endTime: this.queryConditionBackup.month,
        type: this.queryConditionBackup.type,
        hospitalId: this.queryConditionBackup.hospitalId,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }

      followYzyStatisticsQueryInfoCount(params).then(resCount => {
        followYzyStatisticsQueryInfo(params).then(res => {
          this.tableData = res.data
          this.count = resCount.data
          this.tableLoading = false
        })
      })
    },

    /*
     *重置分页信息
     */
    recoverParams() {
      this.pageNum = 1
      this.pageSize = 10
      this.count = 0
    },

    handleSizeChange(val) {
      this.queryDetailsTable()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.queryDetailsTable()
      console.log(`当前页: ${val}`)
    },

    /*
     *  生成echart饼图
     */
    echartPie() {
      const option = {
        title: {
          text: this.chartData.titleText,
          // subtext: '副标题',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} <br/>{c}  占比({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 30,
          data: this.chartData.legendData
        },
        series: [
          {
            name: '',
            type: 'pie',
            top: 50,
            radius: ['0%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'inner'
            },
            data: this.chartData.data
          }
        ]
      }
      const chart = this.$refs.chart
      if (chart) {
        const myChart = echarts.init(chart)
        myChart.off('click') // 解除click！解决重复点击
        myChart.setOption(option)
        myChart.on('click', params => {
          this.recoverParams()
          this.tableData = []
          this.monthTableData = []
          this.tableLoading = true
          this.queryConditionBackup.type = params.data.type
          this.queryList()
          // console.log(params)
        })
      }
    },

    /* 跳转查看*/
    getRowKey(row) {
      this.$router.push({
        path: '/follow-up/follow-up-details',
        query: {
          patId: row.pat_id,
          // memPatTypeCodes: row.patTypeCode,
          activeName: 'first'
        }
      })
    },
    /*
     *重置查询条件
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style>
.dividerLine {
  position: relative;
  top: -20px;
}
.echarts-dom {
  width: 100%;
  height: 500px;
}
.pointerEvents {
  pointer-events: none;
}
</style>
